#!/usr/bin/evn python

import os,commands, requests, re
import sys

GDOCKER_URL = "http://gdocker.uat.ds.gome.com.cn"
HOSTNAME = os.popen('hostname').read().strip()
#WEBSSH_CHECK_URL = "http://10.114.249.4:4200/domeos/health"
WEBSSH_CHECK_URL = "http://10.113.10.17:4200/domeos/health"

def k8s_master_status():
  ret_list = []
  api_healthz_url = "http://127.0.0.1:8080/healthz"
  api_status = requests.get(api_healthz_url).text
  if api_status == "ok":
    ret_list.append({"hostname": HOSTNAME, "component": "apiserver", "status": "True"})
  else:
    ret_list.append({"hostname": HOSTNAME, "component": "apiserver", "status": "False"})
    return ret_list
  url = "http://127.0.0.1:8080/api/v1/componentstatuses/"
  r = requests.get(url)
  result = r.json()
  for item in result["items"]:
    ins = {"hostname": HOSTNAME,"component": item["metadata"]["name"].encode('utf-8'), "status": item["conditions"][0]["status"].encode('utf-8')}
    ret_list.append(ins)
  return ret_list

def k8s_minion_status():
  ret_list = []
  url_kubelet = "http://localhost:10248/healthz"
  url_kubeproxy = "http://localhost:10249/healthz"
  r_kubelet = requests.get(url_kubelet).text
  if r_kubelet == "ok":
    ret_list.append({"hostname": HOSTNAME,"component": "kubelet", "status": "True"})
  else:
    ret_list.append({"hostname": HOSTNAME,"component": "kubelet", "status": "False"})
    
  r_kubeproxy = requests.get(url_kubeproxy).text
  if r_kubeproxy == "ok":
    ret_list.append({"hostname": HOSTNAME,"component": "kube-proxy", "status": "True"})
  else:
    ret_list.append({"hostname": HOSTNAME,"component": "kube-proxy", "status": "False"})
  return ret_list

def calico_status():
  ret_list = []
  (status, output) = commands.getstatusoutput("calicoctl node status")
  if status != 0:
    ret_list.append({"hostname": HOSTNAME,"component": "calico", "status": "False"})
  else:
    if "running" in output and "up" in output and "Established" in output:
      ret_list.append({"hostname": HOSTNAME,"component": "calico", "status": "True"})
    else:
      ret_list.append({"hostname": HOSTNAME,"component": "calico", "status": "False"})
  return ret_list

def webssh_status():
  try:
    r = requests.get(WEBSSH_CHECK_URL, timeout=1)
    if "ok" in r.text:
        return [{"hostname": "","component": "webssh", "status": "True"}]
  except Exception as e:
    pass

  return [{"hostname": "", "component": "webssh", "status": "False"}]

def get_cookie():
  login_url = GDOCKER_URL + "/api/user/login"
  payload = {"username": "admin", "password": "admin", "loginType": "USER"}
  r = requests.post(login_url, json=payload)
  if r.status_code == 200:
    return r.cookies["JSESSIONID"]
  return False

def send_to_gdocker(payload):
  sessionid = get_cookie()
  if sessionid:
    send_url = GDOCKER_URL + "/api/monitor/componentstatus"
    cookies = dict(JSESSIONID=sessionid)
    r = requests.post(send_url, json=payload, cookies=cookies)
    return r.json()["resultCode"]
  return False

if __name__ == "__main__":
  monitor_result = []
  if len(sys.argv) < 2:
    print "must take 1 args in master, minion, calico, webssh, multi args seprate by comma(,)"
    sys.exit(1)
  monitor_items = sys.argv[1].split(",")
  for item in monitor_items:
    if item == "master":
      monitor_result += k8s_master_status()
    if item == "minion":
      monitor_result += k8s_minion_status()
    if item == "calico":
      monitor_result += calico_status()
    if item == "webssh":
      monitor_result += webssh_status()
 
  aa = send_to_gdocker(monitor_result)
  print aa
